import LoadInfo from '@/components/LoadInfo';
import { queryCompanies } from '@/pages/SystemUser/service';
import { specialCharReg, urlReg } from '@/utils/utils';
import {
  ProForm,
  ModalForm,
  ProFormSelect,
  ProFormSwitch,
  ProFormText,
  ProFormTextArea,
  ProFormUploadButton,
} from '@ant-design/pro-components';
import { Button, message } from 'antd';
import { useState } from 'react';
import { uploadPkg } from '../service';
import { PackageStatusEnum, PackageTypeEnum } from '../types.d';

const UploadPkg = (props: { reload: () => void; isAdmin: boolean }) => {
  const { isAdmin, reload } = props;
  const [ifUrl, setIfUrl] = useState<boolean>(false);
  const [loading, setLoading] = useState<boolean>(false);
  return (
    <ModalForm<{
      pkName: string;
      desc?: string;
      version: string;
      type: PackageTypeEnum;
      ownerId?: string;
      isLast: boolean;
      status: PackageStatusEnum;
      url?: string;
      pkg: any[];
    }>
      layout="vertical"
      title="上传包"
      trigger={<Button type="primary">上传包</Button>}
      modalProps={{
        destroyOnClose: true,
        maskClosable: false,
      }}
      onFinish={async (values) => {
        // message.loading({ key: 'upload_pkg', content: '正在处理，请稍后...' });
        setLoading(true);
        const form = new FormData();
        if (values.url) {
          form.append('url', values.url);
        } else if (values.pkg && values.pkg.length > 0) {
          form.append('pkg', values.pkg[0].originFileObj);
        }
        if (values.ownerId) form.append('ownerId', values.ownerId);
        if (values.desc) form.append('desc', values.desc);
        form.append('pkName', values.pkName);
        form.append('version', values.version);
        form.append('type', String(values.type));
        form.append('isLast', String(values.isLast));
        form.append('status', String(values.status));
        const res = await uploadPkg(form);
        if (res.success) {
          message.success({
            content: res.message,
            key: 'upload_pkg',
          });
          reload();
          setLoading(false);
          return true;
        }
        message.error({ content: res.message, key: 'upload_pkg' });
        setLoading(false);
        return false;
      }}
    >
      {loading ? (
        <LoadInfo
          loading={loading}
          action={() => {}}
          actionText=""
          loadingText="正在处理，请稍后..."
        />
      ) : (
        <>
          {isAdmin && (
            <ProFormSelect
              width="xl"
              name="ownerId"
              label="归属公司"
              debounceTime={300}
              showSearch
              placeholder="请选择归属公司(如未找到目标公司，请优先创建[企业管理者])"
              request={(val) => queryCompanies(val.keyWords)}
            />
          )}
          <ProFormText
            name="pkName"
            label="包名称"
            width="xl"
            placeholder="请输入当前包名称(请确保当前包名唯一性, 且不支持特殊字符)"
            rules={[
              {
                required: true,
                validator: (_, val) => {
                  if (!val || specialCharReg.test(val))
                    return Promise.reject(new Error('包名不符合规范，不支持包含特殊字符'));
                  return Promise.resolve(val);
                },
              },
            ]}
          />
          <ProForm.Group>
            <ProFormText
              name="version"
              label="版本号"
              width="md"
              placeholder="当前包的版本号, 例如1.0.0、1.1.0-alpha"
              rules={[
                {
                  required: true,
                  validator: (_, val) => {
                    if (!val || !/^\d+\.\d+.[\w_-]+$/.test(val))
                      return Promise.reject(new Error('版本号不符合规范，请按照x.x.x格式进行填写'));
                    return Promise.resolve(val);
                  },
                },
              ]}
            />
            <ProFormSelect
              name="type"
              label="包类型"
              width="md"
              required
              initialValue={PackageTypeEnum.POS_CHARGE_APK}
              options={[
                {
                  label: '收费平台POS端APP',
                  value: PackageTypeEnum.POS_CHARGE_APK,
                },
              ]}
            />
          </ProForm.Group>
          <ProForm.Group>
            <ProFormSelect
              name="status"
              label="包状态"
              width="md"
              required
              tooltip="当前包的开放状态, 仅当包状态为已开放时, 当前包允许请求下载"
              initialValue={PackageStatusEnum.WAIT}
              options={[
                {
                  label: '待开放',
                  value: PackageStatusEnum.WAIT,
                },
                {
                  label: '已开放',
                  value: PackageStatusEnum.OPEN,
                },
                {
                  label: '已下架',
                  value: PackageStatusEnum.DEPRECATED,
                },
              ]}
            />
            <ProFormSwitch
              label="是否为最新版本"
              name="isLast"
              required
              tooltip="是否将当前版本置为对应包的最新版本"
            />
          </ProForm.Group>
          <ProFormTextArea
            label="版本描述"
            name="desc"
            width="xl"
            placeholder="请输入当前版本说明"
          />
          {ifUrl ? (
            <ProFormText
              name="url"
              label={
                <span>
                  文件地址{' '}
                  <a
                    style={{
                      userSelect: 'none',
                    }}
                    onClick={(e) => {
                      e.preventDefault();
                      e.stopPropagation();
                      setIfUrl(false);
                    }}
                  >
                    返回上传文件
                  </a>
                </span>
              }
              rules={[
                {
                  required: true,
                  validator: (_, val) => {
                    if (!val || !urlReg.test(val)) return Promise.reject(new Error('无效的地址'));
                    return Promise.resolve(val);
                  },
                },
              ]}
              width="xl"
              placeholder="请输入文件下载地址"
            />
          ) : (
            <ProFormUploadButton
              required
              label={
                <span>
                  上传文件{' '}
                  <a
                    style={{
                      userSelect: 'none',
                    }}
                    onClick={(e) => {
                      e.preventDefault();
                      e.stopPropagation();
                      setIfUrl(true);
                    }}
                  >
                    已有文件链接? 点击此处输入
                  </a>
                </span>
              }
              title="选择文件"
              name="pkg"
              listType="text"
              fieldProps={{
                maxCount: 1,
                customRequest: () => {},
                beforeUpload: (): Promise<boolean> =>
                  new Promise((resolve) => {
                    resolve(false);
                  }),
              }}
            />
          )}
        </>
      )}
    </ModalForm>
  );
};

export default UploadPkg;
